import { reqGetCategory1List, type category1ListType, reqGetCategory2List, type category2ListType, reqGetCategory3List, type category3ListType } from "@/api/category"
import { defineStore } from "pinia"

interface stateType {
    category1List: category1ListType;
    category2List: category2ListType;
    category3List: category3ListType

    category1Id: number | null;
    category2Id: number | null;
    category3Id: number | null;

}

export default defineStore("category", {
    state: (): stateType => {
        return {
            category1List: [],
            category2List: [],
            category3List: [],

            category1Id: null,
            category2Id: null,
            category3Id: null,

        };
    },
    actions: {
        // 请求一级分类列表
        async getCategory1List() {
            try {
                const result = await reqGetCategory1List();
                this.category1List = result;
            } catch (e) {
                return Promise.reject(e)
            }
        },

        // 请求二级分类列表
        async getCategory2List() {
            try {
                // 一级列表发生改变，二级和三级数据清空
                this.category2List = [];
                this.category3List = [];
                this.category2Id = null;
                this.category3Id = null;

                const result = await reqGetCategory2List(this.category1Id!);
                this.category2List = result;
            } catch (e) {
                return Promise.reject(e)
            }
        },

        // 请求三级分类列表
        async getCategory3List() {
            try {
                // 二级列表发生改变，三级数据清空
                this.category3List = [];
                this.category3Id = null;

                const result = await reqGetCategory3List(this.category2Id!);
                this.category3List = result;
            } catch (e) {
                return Promise.reject(e)
            }
        }
    }
})